package com.ly.auth.controller.oauth;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class AuthLoginController {

    @Autowired
    private ServletContext servletContext;

    @RequestMapping("/loginPage")
    public String loginPage(Model model) {
        String contextPath = servletContext.getContextPath();
        model.addAttribute("contextPath", contextPath);
        return "login";
    }

    @RequestMapping("/failed")
    public String failed(HttpServletRequest request, HttpServletResponse response, Model model) {
        AuthenticationException exception = (AuthenticationException) request.getSession().getAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        if (exception != null) {
            if (exception instanceof BadCredentialsException) {
                // 密码错误
                // 这里可以进行相应操作，例如返回错误提示信息
            } else if (exception instanceof AccountExpiredException) {
                // 账号过期
                // ...
            } else if (exception instanceof LockedException) {
                // 账户被锁定
                // ...
            }
        }

        String contextPath = servletContext.getContextPath();
        model.addAttribute("contextPath", contextPath);
        return "login";
    }

    @RequestMapping("/success")
    public String success(Model model, Authentication authentication) {
        String contextPath = servletContext.getContextPath();
        model.addAttribute("contextPath", contextPath);
        return "main";
    }

    @RequestMapping("/login")
    public String login(Model model) {
        String contextPath = servletContext.getContextPath();
        model.addAttribute("contextPath", contextPath);
        return "login";
    }


}
